﻿using Abp.Application.Services;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using Abp.Runtime.Validation;
using Abp.UI;
using Camc.Quality.Inspection.InspectionStrat;
using Camc.Quality.Quality;
using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace Camc.Quality.Inspection
{
    /// <summary>
    /// 文件通用的接口 实现
    /// </summary>
    public class InspectionFileCommonService : ApplicationService, IInspectionFileCommonService
    {
        private readonly IRepository<InspectionStandardDesc, Guid> _inspectionStandardDescRepository;
        private readonly IRepository<UploadPicture, Guid> _uploadPictureRepository;
        private readonly IUnitOfWorkManager _unitOfWorkManager;
        public InspectionFileCommonService(IRepository<InspectionStandardDesc, Guid> inspectionStandardDescRepository,
            IRepository<UploadPicture, Guid> uploadPictureRepository,
            IUnitOfWorkManager unitOfWorkManager
            )
        {
            _inspectionStandardDescRepository = inspectionStandardDescRepository;
            _uploadPictureRepository = uploadPictureRepository;
            _unitOfWorkManager = unitOfWorkManager;
        }
        /// <summary>
        /// 上传一个文件，并返回文件上传成功后的信息
        /// </summary>
        /// <param name="uploadedFile"></param>
        /// <param name="taskCode"></param>
        /// <returns></returns>
        public async Task<InspectionFileUploadDto> InspectionUploadFile(IFormFile uploadedFile ,string taskCodeode)
        {
            try
            {
                if (uploadedFile != null)
                {
                    //文件的原始名称
                    string formFileName = uploadedFile.FileName;
                    if (!new[] { ".png", ".jpg", ".bmp" }.Any((item) => formFileName.ToLower().EndsWith(item)))
                    {
                        throw new AbpValidationException("您上传的文件格式必须为png、jpg、bmp中的一种");
                    }
                    //文件保存的路径(应用的工作目录+文件夹相对路径);
                    string fileSavePath = Environment.CurrentDirectory + "\\wwwroot\\Inspection\\";
                    if (!Directory.Exists(fileSavePath))
                    {
                        Directory.CreateDirectory(fileSavePath);
                    }
                    //生成文件的名称
                    string filePath = Path.Combine(fileSavePath, formFileName);
                    using (var fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        uploadedFile.CopyTo(fileStream);
                        fileStream.Flush();
                    }
                    UploadPicture uploadPicture = new UploadPicture();
                    {
                        uploadPicture.Id = Guid.NewGuid();
                        uploadPicture.Organization = Organizations.默认;
                        uploadPicture.Group = Groups.异常管理;
                        uploadPicture.FileName = formFileName;
                        uploadPicture.FileUrl = filePath;
                        uploadPicture.Size = uploadedFile.Length;
                    }
                    //保存图片资料到数据库
                    await _uploadPictureRepository.InsertAndGetIdAsync(uploadPicture);
                    _unitOfWorkManager.Current.SaveChanges();
                    //返回上传图片信息
                    InspectionFileUploadDto result = new InspectionFileUploadDto();
                    {
                        result.Id = uploadPicture.Id;
                        result.FileName = formFileName;
                        result.FileUrl = fileSavePath + "\\" + formFileName;
                    }
                    result.IFormFile = uploadedFile;
                    return result;
                }
                else
                {
                    throw new UserFriendlyException("文件不能为空");
                }
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException("文件上传失败，原因" + ex.Message);
            }
        }
        /// <summary>
        /// 删除图片
        /// </summary>
        /// <param name="id"></param>
        /// <param name="fileName"></param>
        /// <param name="taskCode"></param>
        /// <returns></returns>
        public async Task DeleteImage(Guid id, string fileName, string taskCode)
        {
            var file = _uploadPictureRepository.FirstOrDefault(s => s.Id == id);
            string fileSavePath = Environment.CurrentDirectory + "\\wwwroot\\Inspection\\";
            string filePath = Path.Combine(fileSavePath, fileName);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            if (file != null)
            {
                await _uploadPictureRepository.DeleteAsync(file);
            }
        }
    }
}
